#include "pch.hpp"

#include "Player.h" 
#include "animation.h"

static animation walking_anim;
static animation holding_anim;
static float player_time = 0;
static sf::Clock player_anim_clock;

float WrapAngle(float angle)
{
	while(angle<-PI)
		angle += 2*PI;
	while(angle>PI)
		angle -= 2*PI;

	return angle;
}

Player::Player(): held_ball(false), throw_timer(999)
{
}

void Player::load(float radius)
{
	circle_radius = radius;
	image.LoadFromFile("data/player.png");
	sprite.SetImage(image);
	sprite.SetCenter(32, 32);
	curr_angle = 0;
	walking_anim.load("data/animacja_chodzenie_chopek.png", 100, 100, 8, 100, true);
	holding_anim.load("data/chopek_hold.png", 100, 100, 1, 100, true);
	walking = false;
	throw_image.LoadFromFile("data/chopek_throw.png");
	throw_sprite.SetImage(throw_image);
	throw_sprite.SetCenter(throw_image.GetWidth()/2.0f,throw_image.GetHeight()/2.0f);
}

void Player::step(float x, float y)
{
	throw_timer += 1/60.0f;

	y -= 768/2.0f;

	float length = sqrt(x*x+y*y);

	if(length<1)
	{
		length = 1;
		y = -1;
		x = 0;
	}

	float angle = acos(y/length);
	if(x<0) angle = -angle;

	float last_angle = curr_angle;

	curr_angle = WrapAngle(angle-curr_angle)*0.1f;
	curr_angle += last_angle;
	curr_angle = WrapAngle(curr_angle);

	position.x = sin(curr_angle)*circle_radius;
	position.y = cos(curr_angle)*circle_radius;

	position.y += 768/2.0f;

	float angleDisp = abs(WrapAngle(last_angle-curr_angle));

	if(angleDisp>0.001)
		walking = true;
	else 
		walking = false;
	
	player_time += angleDisp*2;
}

void Player::draw()
{
	if(!held_ball)
	{
		if(throw_timer < 0.25f)
		{
			sf::Vector2f dir(-position.x, -position.y+768/2.0f);
			sfm::Rotate(dir, -90);
			directToVector(throw_sprite,dir);
			throw_sprite.SetPosition(position);
			app.Draw(throw_sprite);
		} else
		{
			walking_anim.SetPos(position);
			sf::Vector2f dir(-position.x, -position.y+768/2.0f);
			sfm::Rotate(dir, -90);
			walking_anim.draw(player_time*1000, dir);
		}
	} else
	{
		holding_anim.SetPos(position);
		sf::Vector2f dir(-position.x, -position.y+768/2.0f);
		sfm::Rotate(dir, -90);
		holding_anim.draw(player_anim_clock.GetElapsedTime()*1000, dir);

		sf::Image &img = GetBallImage(ball_type);
		ball_sprite.SetImage(img);
		ball_sprite.SetCenter(img.GetWidth()/2.0f, img.GetHeight()/2.0f);
		ball_sprite.SetPosition(position);
		directToVector(ball_sprite, -sf::Vector2f(position.x, position.y-768/2.0f), false);
		app.Draw(ball_sprite);
	}
}

bool Player::fire_ball()
{
	if(held_ball)
		throw_timer = 0;
	bool q = held_ball;
	held_ball = false;
	return q;
}

void Player::give_ball(BallType::Type type)
{
	held_ball = true;
	ball_type = type;
}